﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CategoriesViewModel.cs" company="Spenta Consulting">
//   (c) Copyright 2011
// </copyright>
// <summary>
//   Defines the CategoriesViewModel type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Spenta.StreetCare.Silverlight.MVVM.ViewModels
{
    #region Using Directives

    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Windows.Browser;
    using System.Windows.Input;
    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;
    using Globals;
    using Messages;

    using Spenta.StreetCare.Silverlight.Logging;

    using StreetCareAPI;

    #endregion

    /// <summary>
    /// Defines the CategoriesViewModel type.
    /// </summary>
    public class CategoriesViewModel : BaseViewModel
    {
        /// <summary>
        /// Private store for the list of categories
        /// </summary>
        private IEnumerable<CategoryWithCount> categoriesWithCount;

        #region Class constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="CategoriesViewModel"/> class.
        /// </summary>
        public CategoriesViewModel()
        {
            if (HtmlPage.IsEnabled)
            {
                ApiClient.GetReportsByCategoryCompleted += this.GetReportsByCategoryCompleted;
                ApiClient.GetCategoriesWithCountCompleted += this.GetCategoriesWithCountCompleted;

                int customerID = Parameters.CustomerID;
                ApiClient.GetCategoriesWithCountAsync(customerID);

                Messenger.Default.Register<NewReportCompletedMessage>(this, this.NewReportCompleted);
            }
        }

        #endregion

        #region ViewModel Properties

        /// <summary>
        /// Gets or sets the categories with count.
        /// </summary>
        /// <value>
        /// The categories with count.
        /// </value>
        public IEnumerable<CategoryWithCount> CategoriesWithCount
        {
            get
            {
                return this.categoriesWithCount;
            }

            set
            {
                this.categoriesWithCount = value;
                RaisePropertyChanged("CategoriesWithCount");
            }
        }

        /// <summary>
        /// Gets the filter by category command.
        /// </summary>
        public ICommand FilterByCategoryCommand
        {
            get
            {
                return new RelayCommand<int>(this.FilterByCategory);
            }
        }

        #endregion

        #region Event Methods

        /// <summary>
        /// Handles the new report completed event.
        /// </summary>
        /// <param name="message">The message.</param>
        public void NewReportCompleted(NewReportCompletedMessage message)
        {
            if (message.IsError)
            {
                return;
            }

            var report = message.Report;

            foreach (var element in
                this.categoriesWithCount.Where(element => element.CategoryID.Equals(report.ReportCategoryID)))
            {
                element.ReportCount++;
            }

            RaisePropertyChanged("CatetegoriesWithCount");
        }

        /// <summary>
        /// Filters the map pushpins by status id
        /// </summary>
        /// <param name="categoryID">The category ID.</param>
        public void FilterByCategory(int categoryID)
        {
            foreach (var element in this.CategoriesWithCount.Where(element => element.CategoryID.Equals(categoryID)))
            {
                element.IsDirty = true;
            }

            ApiClient.GetReportsByCategoryAsync(categoryID);
        }

        /// <summary>
        /// Handles the get categories with count completed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Spenta.StreetCare.Silverlight.StreetCareAPI.GetCategoriesWithCountCompletedEventArgs"/> instance containing the event data.</param>
        private void GetCategoriesWithCountCompleted(object sender, GetCategoriesWithCountCompletedEventArgs e)
        {
            try
            {
                if (e.Result.IsFault)
                {
                    LogHelper.Logger.WriteError("Error getting categories", e.Result.Fault.Exception);
                    return;
                }
            }
            catch (TargetInvocationException ex)
            {
                LogHelper.Logger.WriteError("Error getting categories", ex.InnerException ?? ex);
            }

            this.CategoriesWithCount = e.Result.CategoriesWithCount;

            Messenger.Default.Send(this.categoriesWithCount);
        }

        /// <summary>
        /// Handles the get reports by category completed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Spenta.StreetCare.Silverlight.StreetCareAPI.GetReportsByCategoryCompletedEventArgs"/> instance containing the event data.</param>
        private void GetReportsByCategoryCompleted(object sender, GetReportsByCategoryCompletedEventArgs e)
        {
            try
            {
                if (e.Result.IsFault)
                {
                    LogHelper.Logger.WriteError("Error getting reports", e.Result.Fault.Exception);
                    return;
                }
            }
            catch (TargetInvocationException ex)
            {
                LogHelper.Logger.WriteError("Error getting reports", ex.InnerException ?? ex);
                return;
            }

            foreach (var element in this.categoriesWithCount)
            {
                element.IsDirty = false;
            }

            Messenger.Default.Send(e.Result.Reports);
        }

        #endregion
    }
}
